package cn.hdu.goods.order.dao;

import cn.hdu.goods.book.domain.Book;
import cn.hdu.goods.order.domain.Order;
import cn.hdu.goods.order.domain.OrderItem;
import cn.hdu.goods.pager.Expression;
import cn.hdu.goods.pager.PageBean;
import cn.hdu.goods.pager.PageConstants;
import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OrderDao {

    private QueryRunner qr = new TxQueryRunner();

    public PageBean<Order> findByUser(String uid, int pc) throws SQLException {
        List<Expression> exprList = new ArrayList<>();
        exprList.add(new Expression("uid", "=", uid));
        return findByCriteria(exprList, pc);
    }

    /**
     * 生成订单
     *
     * @param order
     */
    public void add(Order order) throws SQLException {
        String sql = "insert into t_order values(?,?,?,?,?,?)";
        Object[] params = {order.getOid(), order.getOrdertime(), order.getTotal(),
                order.getStatus(), order.getAddress(), order.getOwner().getUid()};
        qr.update(sql, params);

        String itemSql = "insert into t_orderitem values(?,?,?,?,?,?,?,?)";
        int len = order.getOrderItemList().size();
        Object[][] objs = new Object[len][];
        for (int i = 0; i < len; i++) {
            OrderItem item = order.getOrderItemList().get(i);
            objs[i] = new Object[]{item.getOrderItemId(), item.getQuantity(),
                    item.getSubtotal(), item.getBook().getBid(), item.getBook().getBname(),
                    item.getBook().getCurrPrice(), item.getBook().getImage_b(), order.getOid()};
        }
        qr.batch(itemSql, objs);
    }

    public Order load(String oid) throws SQLException {
        String sql = "select * from t_order WHERE oid=?";
        Order order = qr.query(sql, new BeanHandler<>(Order.class), oid);
        loadOrderItem(order);
        return order;
    }

    public int findStatus(String oid) throws SQLException {
        String sql = "select status from t_order WHERE oid=?";
        Number number = (Number) qr.query(sql, new ScalarHandler(), oid);
        return number.intValue();
    }

    public void updateStatus(String oid, int status) throws SQLException {
        String sql = "update t_order set status=? where oid=?";
        qr.update(sql, status, oid);
    }


    private PageBean<Order> findByCriteria(List<Expression> exprList, int pc) throws SQLException {

        /**
         * 1.得到ps
         * 2.得到tr
         * 3.得到beanList
         * 4.创建pagebean，返回
         */
        int ps = PageConstants.ORDER_PAGE_SIZE;

        StringBuilder whereSql = new StringBuilder(" where 1=1");
        List<Object> params = new ArrayList<>();//SQL中问号的值
        for (Expression expr : exprList) {
            whereSql.append(" AND ").
                    append(expr.getName()).append(" ").
                    append(expr.getOperator()).append(" ");
            if (!expr.getOperator().equals("is null")) {
                whereSql.append("?");
                params.add(expr.getValue());
            }
        }

        String sql = "SELECT COUNT(*) FROM t_order" + whereSql;
        Number number = qr.query(sql, new ScalarHandler<>(), params.toArray());
        int tr = number.intValue();

        sql = "select * from t_order" + whereSql + " ORDER BY ordertime desc limit ?,?";
        params.add((pc - 1) * ps);
        params.add(ps);

        //虽然获取了所有订单，但是没个订单中没有订单条目
        List<Order> orderList = qr.query(sql, new BeanListHandler<>(Order.class), params.toArray());
        //遍历没个订单，为其加载他的所有订单条目
        for (Order order : orderList) {
            loadOrderItem(order);
        }

        PageBean<Order> pb = new PageBean<>();
        pb.setBeanList(orderList);
        pb.setPc(pc);
        pb.setPs(ps);
        pb.setTr(tr);
        return pb;
    }

    private void loadOrderItem(Order order) throws SQLException {
        String sql = "select * from t_orderitem WHERE oid=?";

        List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), order.getOid());
        List<OrderItem> orderItemList = toOrderItemList(mapList);
        order.setOrderItemList(orderItemList);

    }

    private List<OrderItem> toOrderItemList(List<Map<String, Object>> mapList) {
        List<OrderItem> orderItemList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            OrderItem orderItem = toOrderItem(map);
            orderItemList.add(orderItem);
        }
        return orderItemList;
    }

    private OrderItem toOrderItem(Map<String, Object> map) {
        OrderItem orderItem = CommonUtils.toBean(map, OrderItem.class);
        Book book = CommonUtils.toBean(map, Book.class);
        orderItem.setBook(book);
        return orderItem;
    }

}
